'use strict';
const crypto = require('crypto');

exports.main = async (event, context) => {
  const { username, password, phone } = event;
  
  // 参数校验
  if (!username || !password || !phone) {
    return {
      code: 1,
      msg: '请填写完整信息'
    }
  }
  
  const db = uniCloud.database();
  const collection = db.collection('users');
  
  try {
    // 检查用户名是否已存在
    const usernameDup = await collection.where({
      username: username
    }).get();
    
    if (usernameDup.data.length > 0) {
      return {
        code: 2,
        msg: '用户名已存在'
      }
    }
    
    // 检查手机号是否已存在
    const phoneDup = await collection.where({
      phone: phone
    }).get();
    
    if (phoneDup.data.length > 0) {
      return {
        code: 3,
        msg: '手机号已注册'
      }
    }
    
    // 密码加密
    const salt = crypto.randomBytes(16).toString('hex');
    const hash = crypto.pbkdf2Sync(password, salt, 1000, 64, 'sha512').toString('hex');
    
    // 创建用户
    const result = await collection.add({
      username,
      phone,
      password: hash,
      salt,
      create_date: Date.now(),
      status: 1
    });
    
    return {
      code: 0,
      msg: '注册成功',
      data: {
        userId: result.id
      }
    }
    
  } catch (e) {
    return {
      code: -1,
      msg: '注册失败，请稍后重试'
    }
  }
}; 